`ifndef REGS_V
`define REGS_V


`include "defines.v"

module regs(
    input  wire clk,
    input  wire rstn,

    // from id
    input  wire[`RegAddrWidth - 1 : 0]  reg1_raddr_i,
    input  wire[`RegAddrWidth - 1 : 0]  reg2_raddr_i,

    // to id
    output reg[`RegDataWidth - 1 : 0]   reg1_rdata_o,
    output reg[`RegDataWidth - 1 : 0]   reg2_rdata_o,

    // from ex
    input  wire[`RegAddrWidth - 1 : 0]  waddr_i,
    input  wire[`RegDataWidth - 1 : 0]  wdata_i,
    input  wire                         wen_i
);

reg[`RegDataWidth - 1 : 0] GPR[0 : `RegNum - 1]; // regs: x0,x1,...,x31

// 写数据
always @(posedge clk or negedge rstn) begin
    if(rstn == 1'b0) begin

    end
    // protect reg x0
    else if((wen_i == 1'b1) && (waddr_i != `R_X0_ADDR)) begin
        GPR[waddr_i] <= wdata_i;
    end
end

// 读寄存器 1
always @(*) begin
    if(reg1_raddr_i == `R_X0_ADDR) begin
        reg1_rdata_o = `R_X0_DATA;
    end
    // 避免读写冲突
    else if((reg1_raddr_i == waddr_i) && (wen_i == 1'b1)) begin
        reg1_rdata_o = wdata_i;
    end
    else begin
        reg1_rdata_o = GPR[reg1_raddr_i];
    end
end

// 读寄存器 2
always @(*) begin
    if(reg2_raddr_i == `R_X0_ADDR) begin
        reg2_rdata_o = `R_X0_DATA;
    end
    // 避免读写冲突
    else if((reg2_raddr_i == waddr_i) && (wen_i == 1'b1)) begin
        reg2_rdata_o = wdata_i;
    end
    else begin
        reg2_rdata_o = GPR[reg2_raddr_i];
    end
end

endmodule


`endif // REGS_V